package net.wwang.utils;

import net.wwang.config.FileUpdateFrame;
import org.apache.log4j.Logger;
import org.gjt.jclasslib.io.ClassFileWriter;
import org.gjt.jclasslib.structures.CPInfo;
import org.gjt.jclasslib.structures.ClassFile;
import org.gjt.jclasslib.structures.constants.ConstantUtf8Info;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
*
* @description: create by wangwei：修改字节码文件
*/
public class UpdateClassUtil {
    private static Logger logger = Logger.getLogger(UpdateClassUtil.class);
    public static void updateClass(String filePath,String str, int index) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        DataInput di = new DataInputStream(fis);
        ClassFile cf = new ClassFile();
        cf.read(di);
        CPInfo[] infos = cf.getConstantPool();
        int count = infos.length;
        for (int i = 0; i < count; i++) {
            if (infos[i] != null) {
                logger.info(i);
                logger.info(" = ");
                logger.info(infos[i].getVerbose());
                logger.info(" = ");
                logger.info(infos[i].getTagVerbose());
                if (i == index) {

                    ConstantUtf8Info utf8Info = (ConstantUtf8Info) infos[i];
                    utf8Info.setBytes((str).getBytes());
                    infos[i] = utf8Info;
                }

            }
        }
        cf.setConstantPool(infos);
        fis.close();
        File f = new File(filePath);
        ClassFileWriter.writeToFile(f, cf);

    }
}
